<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑角色' : '新增角色' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
        v-loading="loading"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="角色标识" prop="name">
              <el-input 
                v-model="form.name" 
                placeholder="请输入角色标识，如admin" 
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="角色名称" prop="displayName">
              <el-input v-model="form.displayName" placeholder="请输入角色名称，如系统管理员" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="启用" />
                <el-option label="禁用" value="禁用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input 
                v-model="form.description" 
                placeholder="请输入角色描述" 
                type="textarea"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">权限设置</el-divider>
        
        <el-form-item label="角色权限" prop="permissions">
          <div class="permissions-container">
            <template v-for="(group, groupName) in permissionGroups" :key="groupName">
              <div class="permission-group">
                <div class="group-header">
                  <el-checkbox 
                    v-model="checkAllMap[groupName]"
                    :indeterminate="isIndeterminate(groupName)"
                    @change="(val) => handleCheckAllChange(val, groupName)"
                  >
                    {{ groupName }}
                  </el-checkbox>
                </div>
                <div class="permission-list">
                  <el-checkbox-group v-model="form.permissions" @change="handleCheckedChange">
                    <el-checkbox 
                      v-for="permission in group" 
                      :key="permission.code"
                      :label="permission.code"
                      border
                    >
                      {{ permission.name }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </template>
          </div>
        </el-form-item>
        
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { roleAPI } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const roleId = ref(route.params.id)
const isEdit = computed(() => !!roleId.value)

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 表单数据
const form = reactive({
  name: '',
  displayName: '',
  description: '',
  status: '启用',
  permissions: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '角色标识只能包含小写字母、数字和下划线，且必须以字母开头', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 权限数据
const permissionList = ref([])
const permissionGroups = ref({})
const checkAllMap = ref({})

// 将权限列表按模块分组
const groupPermissions = (permissions) => {
  const groups = {}
  
  permissions.forEach(permission => {
    // 如果是简单字符串格式的权限 (如 "user:read")
    if (typeof permission === 'string') {
      const parts = permission.split(':')
      if (parts.length >= 2) {
        const groupName = parts[0].charAt(0).toUpperCase() + parts[0].slice(1) // 首字母大写
        const actionName = parts[1]
        
        if (!groups[groupName]) {
          groups[groupName] = []
        }
        
        groups[groupName].push({
          code: permission,
          name: getActionDisplayName(actionName)
        })
      } else {
        // 如果格式不符合预期，放入"其他"分组
        if (!groups['其他']) {
          groups['其他'] = []
        }
        groups['其他'].push({
          code: permission,
          name: permission
        })
      }
    } 
    // 如果是对象格式的权限
    else if (permission.code) {
      const groupName = permission.group || '其他'
      if (!groups[groupName]) {
        groups[groupName] = []
      }
      groups[groupName].push(permission)
    }
  })
  
  return groups
}

// 获取操作的显示名称
const getActionDisplayName = (action) => {
  const actionMap = {
    'read': '查看',
    'create': '创建',
    'update': '更新',
    'delete': '删除',
    'audit': '审核',
    'dispense': '发放',
    'checkin': '签到',
    'payment': '支付',
    'execute': '执行',
    'generate': '生成',
    'upload': '上传'
  }
  
  return actionMap[action] || action
}

// 获取角色详情
const fetchRoleDetail = async () => {
  if (!roleId.value) return
  
  loading.value = true
  try {
    const res = await roleAPI.getRole(roleId.value)
    console.log('角色详情API响应:', res)
    
    // 处理不同的响应格式
    let roleData = null
    
    if (res.success) {
      roleData = res.data
    } else if (res.data && res.data.success) {
      roleData = res.data.data
    } else if (res.data) {
      // 直接返回了角色对象
      roleData = res.data
    } else {
      // 尝试直接使用响应本身作为角色数据
      roleData = res
    }
    
    if (roleData && (roleData.id || roleData._id)) {
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (roleData[key] !== undefined) {
          form[key] = roleData[key]
        }
      })
      
      // 更新全选状态
      updateCheckAllStatus()
    } else {
      ElMessage.error('获取角色详情失败：角色数据为空')
      console.error('角色数据无效:', roleData)
    }
  } catch (error) {
    console.error('获取角色详情失败', error)
    ElMessage.error('获取角色详情失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    const res = await roleAPI.getPermissions()
    console.log('权限列表API响应:', res)
    
    // 处理不同的响应格式
    let permissions = []
    
    if (res.success) {
      permissions = res.data.permissions || []
    } else if (res.data && res.data.success) {
      permissions = res.data.data.permissions || []
    } else if (Array.isArray(res)) {
      // 直接返回了权限数组
      permissions = res
    } else if (Array.isArray(res.data)) {
      // data字段是权限数组
      permissions = res.data
    } else {
      console.error('获取权限列表失败：响应格式不正确', res)
      return
    }
    
    // 如果是您提供的权限列表，直接使用
    if (permissions.length === 0) {
      permissions = [
        "user:read", "user:create", "user:update", "user:delete",
        "role:read", "role:create", "role:update", "role:delete",
        "department:read", "department:create", "department:update", "department:delete",
        "patient:read", "patient:create", "patient:update", "patient:delete",
        "doctor:read", "doctor:create", "doctor:update", "doctor:delete",
        "drug:read", "drug:create", "drug:update", "drug:delete",
        "medical_record:read", "medical_record:create", "medical_record:update", "medical_record:delete",
        "prescription:read", "prescription:create", "prescription:update", "prescription:audit", "prescription:dispense",
        "appointment:read", "appointment:create", "appointment:update", "appointment:delete", "appointment:checkin", "appointment:payment",
        "schedule:read", "schedule:create", "schedule:update", "schedule:delete",
        "drug_inventory:read", "drug_inventory:create", "drug_inventory:update",
        "medical_order:read", "medical_order:create", "medical_order:update", "medical_order:delete", "medical_order:execute",
        "report:read", "report:generate",
        "payment:read", "payment:create", "payment:update",
        "invoice:read", "invoice:create", "invoice:update",
        "file:upload", "file:read", "file:delete"
      ]
    }
    
    permissionList.value = permissions
    permissionGroups.value = groupPermissions(permissionList.value)
    
    // 初始化全选状态映射
    Object.keys(permissionGroups.value).forEach(groupName => {
      checkAllMap.value[groupName] = false
    })
    
    // 如果是编辑模式，更新全选状态
    if (isEdit.value) {
      updateCheckAllStatus()
    }
  } catch (error) {
    console.error('获取权限列表失败', error)
    // 使用默认权限列表
    const defaultPermissions = [
      "user:read", "user:create", "user:update", "user:delete",
      "role:read", "role:create", "role:update", "role:delete",
      "department:read", "department:create", "department:update", "department:delete",
      "patient:read", "patient:create", "patient:update", "patient:delete",
      "doctor:read", "doctor:create", "doctor:update", "doctor:delete",
      "drug:read", "drug:create", "drug:update", "drug:delete",
      "medical_record:read", "medical_record:create", "medical_record:update", "medical_record:delete",
      "prescription:read", "prescription:create", "prescription:update", "prescription:audit", "prescription:dispense",
      "appointment:read", "appointment:create", "appointment:update", "appointment:delete", "appointment:checkin", "appointment:payment",
      "schedule:read", "schedule:create", "schedule:update", "schedule:delete",
      "drug_inventory:read", "drug_inventory:create", "drug_inventory:update",
      "medical_order:read", "medical_order:create", "medical_order:update", "medical_order:delete", "medical_order:execute",
      "report:read", "report:generate",
      "payment:read", "payment:create", "payment:update",
      "invoice:read", "invoice:create", "invoice:update",
      "file:upload", "file:read", "file:delete"
    ]
    permissionList.value = defaultPermissions
    permissionGroups.value = groupPermissions(defaultPermissions)
    
    // 初始化全选状态映射
    Object.keys(permissionGroups.value).forEach(groupName => {
      checkAllMap.value[groupName] = false
    })
    
    // 如果是编辑模式，更新全选状态
    if (isEdit.value) {
      updateCheckAllStatus()
    }
  }
}

// 更新全选状态
const updateCheckAllStatus = () => {
  Object.keys(permissionGroups.value).forEach(groupName => {
    const group = permissionGroups.value[groupName]
    const groupPermissionCodes = group.map(p => typeof p === 'string' ? p : p.code)
    
    // 判断当前组的权限是否全部选中
    const allSelected = groupPermissionCodes.every(code => form.permissions.includes(code))
    const someSelected = groupPermissionCodes.some(code => form.permissions.includes(code))
    
    checkAllMap.value[groupName] = allSelected
  })
}

// 判断是否部分选中
const isIndeterminate = (groupName) => {
  const group = permissionGroups.value[groupName]
  const groupPermissionCodes = group.map(p => typeof p === 'string' ? p : p.code)
  
  const allSelected = groupPermissionCodes.every(code => form.permissions.includes(code))
  const someSelected = groupPermissionCodes.some(code => form.permissions.includes(code))
  
  return someSelected && !allSelected
}

// 全选/取消全选
const handleCheckAllChange = (val, groupName) => {
  const group = permissionGroups.value[groupName]
  const groupPermissionCodes = group.map(p => typeof p === 'string' ? p : p.code)
  
  if (val) {
    // 全选：添加该组所有权限
    form.permissions = [...new Set([...form.permissions, ...groupPermissionCodes])]
  } else {
    // 取消全选：移除该组所有权限
    form.permissions = form.permissions.filter(code => !groupPermissionCodes.includes(code))
  }
}

// 权限选中状态变化
const handleCheckedChange = () => {
  updateCheckAllStatus()
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      // 准备提交的数据
      const roleData = { ...form }
      
      let res
      if (isEdit.value) {
        // 确保ID使用正确的字段
        const id = roleId.value
        res = await roleAPI.updateRole(id, roleData)
      } else {
        res = await roleAPI.createRole(roleData)
      }
      
      console.log(isEdit.value ? '更新角色响应:' : '创建角色响应:', res)
      
      // 处理不同的响应格式
      let success = false
      let message = ''
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      } else if (res.data && res.data.message) {
        message = res.data.message
      } else if (res.message) {
        message = res.message
      }
      
      if (success) {
        ElMessage.success(isEdit.value ? '角色更新成功' : '角色创建成功')
        goBack()
      } else {
        ElMessage.error(message || (isEdit.value ? '角色更新失败' : '角色创建失败'))
      }
    } catch (error) {
      console.error(isEdit.value ? '角色更新失败' : '角色创建失败', error)
      ElMessage.error(isEdit.value ? '角色更新失败' : '角色创建失败')
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  fetchPermissions()
  
  if (isEdit.value) {
    fetchRoleDetail()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}
.permissions-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.permission-group {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  width: 100%;
}
.group-header {
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}
.permission-list {
  display: flex;
  flex-wrap: wrap;
}
.permission-list .el-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}
</style> 